<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          @click="handleAdd"
          v-hasPermi="['project:group:add']"
          >创建楼层</el-button
        >
      </el-col>
    </el-row>
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
      class="header"
    >
      <el-form-item>
        <el-select
          v-model="queryParams.groupId"
          placeholder="请选择所属企业"
          class="affiliatedCompany"
        >
          <el-option
            v-for="dict in dict.type.ly_group"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-select
          v-model="queryParams.projectId"
          placeholder="请选择所属项目"
          clearable
          class="affiliatedProject"
        >
          <el-option
            v-for="item in queryProjectList"
            :label="item.projectName"
            :value="item.id"
            :key="item.id"
          >
            {{ item.projectName }}</el-option
          >
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-select
          v-model="queryParams.banId"
          placeholder="请选择所属楼栋"
          clearable
          class="affiliatedBuild"
        >
          <el-option
            v-for="item in queryBanList"
            :label="item.banName"
            :value="item.banId"
            :key="item.banId"
          >
            {{ item.banName }}</el-option
          >
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-input
          v-model="queryParams.floorNumber"
          placeholder="楼层"
          class="floor"
        >
        </el-input>
      </el-form-item>

      <el-form-item>
        <el-button
          icon="el-icon-refresh"
          class="reset"
          size="mini"
          @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>

      <el-form-item>
        <el-button
          icon="el-icon-search"
          class="search"
          type="primary"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
      </el-form-item>

      <el-form-item>
        <el-button
          class="export"
          type="warning"
          icon="el-icon-upload"
          size="mini"
          @click="handleExport"
        >
          导出
        </el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="floorDataList">
      <el-table-column label="序号" align="center" type="index" />
      <el-table-column label="楼层" align="center" prop="floorNumber" />
      <el-table-column label="所属楼栋" align="center" prop="banName" />
      <el-table-column label="地址" align="center" prop="banAddress" />
      <el-table-column label="所属企业" align="center" prop="groupId">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.ly_group" :value="scope.row.groupId" />
        </template>
      </el-table-column>
      <el-table-column label="所属项目" align="center" prop="projectName" />
      <el-table-column label="楼层面积(㎡)" align="center" prop="floorArea" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdateOrDetail(scope.row, '编辑')"
            v-hasPermi="['project:group:edit']"
            >编辑</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleUpdateOrDetail(scope.row, '详情')"
            v-hasPermi="['project:project:detail']"
            >详情</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['project:group:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改[空间] 楼层对话框 -->
    <el-dialog
      :fullscreen="true"
      :center="true"
      :title="title"
      :visible.sync="open"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="所属项目" prop="projectId">
          <div class="project_content">
            <el-input
              placeholder="点击查询"
              :readonly="true"
              v-model="form.projectName"
            ></el-input>
            <el-button
              type="text"
              class="project-select-button"
              @click="projectSelect"
              v-if="title !== '详情'"
              >查询</el-button
            >
          </div>
        </el-form-item>

        <el-form-item label="所属楼栋" prop="banId">
          <el-select
            placeholder="请选择楼栋"
            v-model="form.banId"
            @change="handleBanChange"
            :disabled="title === '详情'"
            :style="{ width: '33%' }"
          >
            <el-option
              v-for="ban in banList"
              :label="ban.banName"
              :value="ban.banId"
              >{{ ban.banName }}</el-option
            >
          </el-select>
        </el-form-item>

        <el-form-item label="楼层" prop="floorNumber">
          <el-input
            v-model="form.floorNumber"
            :style="{ width: '33%' }"
            :readonly="title === '详情'"
          />
        </el-form-item>

        <el-form-item label="楼层面积" prop="floorArea">
          <el-input
            type="text"
            v-model="form.floorArea"
            oninput="value=value.replace(/[^\d]/g,'')"
            :style="{ width: '33%' }"
            :readonly="title === '详情'"
          >
            <template slot="append">m²</template>
          </el-input>
        </el-form-item>

        <el-form-item label="平面图">
          <el-upload
            multiple
            :file-list="fileList"
            list-type="picture-card"
            :action="uploadUrl"
            :on-success="handleSuccess"
            :on-remove="handleRemove"
            :disabled="title === '详情'"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" v-if="title !== '详情'"
          >确 定</el-button
        >
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="项目查询器" width="60%" :visible.sync="openProjectSelect">
      <ProjectManagement ref="projectRef" :is-component="true" />
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelProjectSelect">取 消</el-button>
        <el-button type="primary" @click="confirmProjectSelect"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listFloor,
  getFloor,
  delFloor,
  addFloor,
  updateFloor,
  exportFloor,
} from "@/api/space/floor";
import {
  getAllBansApi,
  getAllProjectsApi,
  getBanByProjectId,
  getFloorsByProjectIdAndSiteGroupId,
} from "@/api/space/workSpace";
import ProjectManagement from "@/views/project/projectManagement/index.vue";

export default {
  components: { ProjectManagement },
  dicts: ["ly_group"],
  name: "Floor",
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      floorList: [],
      // 总条数
      total: 0,
      // 项目选择器弹出层
      openProjectSelect: false,
      // 用于查询的所有项目列表
      queryProjectList: [],
      // 用于查询的所有楼栋列表
      queryBanList: [],
      // 楼栋列表
      banList: [],
      fileList: [],
      // 文件上传地址
      uploadUrl: process.env.VUE_APP_BASE_API + "/ly/fileUpload",
      // 楼层表格数据
      floorDataList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        page: 1,
        pageSize: 10,
        groupId: null,
        projectId: null,
        banName: null,
        banId: null,
        floorNumber: null,
      },
      imgs: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {

        banId: [
          { required: true, message: "所属楼栋不能为空", trigger: "blur" },
        ],
        floorNumber: [
          { required: true, message: "楼层不能为空", trigger: "blur" },
        ],
        floorArea: [
          { required: true, message: "楼层面积不能为空", trigger: "change" },
        ],
      },
    };
  },
  created() {
    this.getList();
    this.getAllProjects();
    this.getAllBans();
  },
  methods: {
    /** 查询[空间] 楼层列表 */
    getList() {
      this.loading = true;
      listFloor(this.queryParams).then((response) => {
        this.floorDataList = response.data.records;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    /** 查询所有项目列表用于筛选 */
    getAllProjects() {
      getAllProjectsApi().then((res) => {
        this.queryProjectList = res.code === 200 ? res.data : [];
      });
    },
    /** 查询所有楼栋列表用于筛选 */
    getAllBans() {
      getAllBansApi().then((res) => {
        this.queryBanList = res.code === 200 ? res.data : [];
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        floorId: null,
        banId: null,
        floorNumber: null,
        floorArea: null,
        banName: null,
        groupId: null,
        floorAddress: null,
        imgs: [],
      };
      this.fileList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams = {
        page: 1,
        pageSize: 10,
        groupId: null,
        projectId: null,
        banId: null,
        floorNumber: null,
      };
      this.handleQuery();
    },
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.floorId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "创建楼层";
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.form.imgs = JSON.stringify(this.form.imgs);

          if (this.form.floorId != null) {
            updateFloor(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addFloor(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const floorIds = row.floorId || this.ids;
      this.$modal
        .confirm('是否确认删除楼层编号为"' + floorIds + '"的数据项？')
        .then(function () {
          return delFloor(floorIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },

    /** 查询项目信息 */
    projectSelect() {
      this.openProjectSelect = true;
    },
    /** 取消查询项目信息 */
    cancelProjectSelect() {
      this.openProjectSelect = false;
      this.$refs.projectRef.reset();
    },
    /** 确认项目 */
    confirmProjectSelect() {
      const currentProject = this.$refs.projectRef.getCurrentProject();
      this.form.projectName = currentProject.projectName;
      this.form.projectId = currentProject.id;
      this.form.groupId = currentProject.groupId;
      // 获取该项目的所有楼栋信息
      this.getBanList(this.form.projectId);

      // 清空楼栋的初始值
      this.form.banId = null
      this.openProjectSelect = false;
      this.$refs.projectRef.reset();
    },
    /** 获取楼栋列表 */
    getBanList(projectId) {
      getBanByProjectId(projectId).then((res) => {
        this.banList = res.code === 200 ? res.data : [];
      });
    },
    /** 楼栋变化函数 */
    handleBanChange(val) {
      // 获取当前楼栋下的楼层
      this.getFloorList(this.form.projectId, val);
    },
    /** 获取楼层列表 */
    getFloorList(projectId, banId) {
      getFloorsByProjectIdAndSiteGroupId(projectId, banId).then((res) => {
        this.floorList = res.code === 200 ? res.data : [];
      });
    },

    /** 修改/详情按钮操作 */
    handleUpdateOrDetail(row, title) {
      this.reset();
      // 获取楼层详情
      getFloor(row.floorId).then((response) => {
        this.form = response.data;
        this.form.floorId = row.floorId;
        this.form.imgs = this.fileList = JSON.parse(response.data.imgs);
        // 获取对应楼栋
        this.getBanList(this.form.projectId);
        this.title = title;
        this.open = true;
      });
    },

    handleSuccess(response, file, fileList) {
      console.log(file);
      this.form.imgs.push({ name: file.name, url: response.data });
    },
    handleRemove(file) {
      console.log(file);
      this.form.imgs = this.form.imgs.filter((item) => item.url !== file.url);
    },

    /** 导出按钮操作 */
    handleExport() {
      exportFloor().then((res) => {
        // 创建 Blob 对象，用于包含二进制数据
        const blob = new Blob([res]);
        // 创建 a 标签元素，并将 Blob 对象转换成 URL
        const link = document.createElement("a");
        link.href = window.URL.createObjectURL(blob);
        // 设置下载文件的名称
        const date = new Date();
        const now = date.toLocaleDateString();
        link.download = "楼层数据_" + now + "_.xlsx";
        // 模拟点击下载链接
        link.click();
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.header {
  margin-bottom: 5px;
  .affiliatedProject {
    margin-left: 7px;
  }

  .affiliatedBuild {
    margin-left: 7px;
    width: 140px;
  }

  .buildName {
    width: 135px;
    margin-left: 7px;
  }

  .buildAddress {
    width: 135px;
    margin-left: 7px;
  }

  .reset {
    margin-left: 7px;
  }
}

.affiliatedProject {
  margin-left: 7px;
  border: rgb(210, 210, 210);
}

.affiliatedCompany {
}

.buildName {
  width: 135px;
  margin-left: 7px;
}

.buildAddress {
  width: 135px;
  margin-left: 7px;
}

.reset {
  margin-left: 7px;
}

.floor {
  width: 135px;
  margin-left: 7px;
}

.project_content {
  display: flex;
  align-items: center;
  position: relative;
  width: 591px;

  .project-select-button {
    position: absolute;
    right: 10px;
  }
}
</style>
